using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using IMS.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using IMS.Api.Repository;
using Microsoft.Net.Http.Headers;
using IMS.Api.Entity;
using System.Linq;

namespace Admin3000.Backend.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class FilesController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly IRepository<UploadFileInfo> _fileInfoRepository;

        public FilesController(IConfiguration configuration, IRepository<UploadFileInfo> fileInfoRepository)
        {
            _configuration = configuration;
            _fileInfoRepository = fileInfoRepository;
        }

        /// <summary>
        /// 多文件上传接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("uploadfiles")]
        public string UploadFiles(IFormCollection model)
        {
            // 获得当前应用所在的完整路径（绝对路径）
            var filePath = Directory.GetCurrentDirectory();
            // // 获得当前应用所在的完整路径（物理地址）
            // var filePath = AppDomain.CurrentDomain.BaseDirectory;

            // 通过配置文件获得存放文件的相对路径
            string path = _configuration["UploadFilesPath"];

            // 最终存放文件的完整路径
            var preFullPath = Path.Combine(filePath, path);

            // 如果路径不存在，则创建
            if (!Directory.Exists(preFullPath))
            {
                Directory.CreateDirectory(preFullPath);
            }

            var resultPath = new List<string>();
            var uploadfiles = new List<UploadFileInfo>();
            foreach (IFormFile file in model.Files)
            {
                if (file.Length > 0)
                {
                    var fileName = file.FileName;
                    var extName = fileName.Substring(fileName.LastIndexOf("."));//extName包含了“.”
                    var rndName = Guid.NewGuid().ToString("N") + extName;
                    var tempPath = Path.Combine(path, rndName).Replace("\\", "/");
                    using (var stream = new FileStream(Path.Combine(filePath, tempPath), FileMode.CreateNew))//Path.Combine(_env.WebRootPath, fileName)
                    {
                        file.CopyTo(stream);
                    }

                    var tmpFile = new UploadFileInfo
                    {
                        OriginName = fileName,
                        CurrentName = rndName,
                        RelativePath = tempPath,
                        ContentType = file.ContentType
                    };

                    uploadfiles.Add(tmpFile);

                    // 此处地址可能带有两个反斜杠，虽然也能用，比较奇怪，统一转换成斜杠，这样在任何平台都有一样的表现
                    resultPath.Add(tempPath.Replace("\\", "/"));
                }
            }

            _fileInfoRepository.InsertBulk(uploadfiles);

            var res = new
            {
                Data = uploadfiles.Select(x => new { x.Id }),
                Meta = new
                {
                    Msg = "上传成功",
                    Status = 200
                }
            };

            return JsonHelper.Serialize(res);
        }

        [AllowAnonymous]
        [Route("{id}")]
        [HttpGet]
        public FileContentResult Get(int id)
        {
            // 绝对路径
            var currentPath = Directory.GetCurrentDirectory();
            // // 物理路径
            // var currentPath = AppDomain.CurrentDomain.BaseDirectory;
            var fileInfo = _fileInfoRepository.GetById(id);
            if (fileInfo == null)
            {
                return new FileContentResult(new byte[0], "image/jpeg");
            }
            var fullPath = Path.Combine(currentPath, fileInfo.RelativePath);
            using (var sw = new FileStream(fullPath, FileMode.Open))
            {
                // var contenttype = GetContentTypeForFileName(fullPath);
                var contenttype = fileInfo.ContentType;
                var bytes = new byte[sw.Length];
                sw.Read(bytes, 0, bytes.Length);
                sw.Close();
                return new FileContentResult(bytes, contenttype);
            }
        }
    }
}